<template>
  <div class="department-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          总共: {{ total }}条
        </template>
        <!-- 具体页面结构 -->
        <template #rigft>
          <!-- 员工管理 -->
          <el-button v-allow="'import_ecxel'" type="warning" round @click="$router.push('/employees/import')">导入 Excel</el-button>
          <el-button v-allow="'expot_excel'" type="danger" round @click="hExport">导出 Excel</el-button>
          <el-button v-allow="'add_roles'" type="primary" round @click="showDialog=true">新增员工</el-button>
          <!-- <el-button v-if="$store.state.user.userInfo.roles.points" type="primary" round @click="showDialog=true">新增员工</el-button> -->
        </template>
      </PageTools>
      <el-card style="margin-top:20px">
        <el-table
          :data="employees"
          style="width: 100%"
        >
          <el-table-column
            type="index"
            label="序号"
            width="50px"
          />
          <el-table-column
            prop="username"
            label="姓名"
          />
          <el-table-column label="头像">
            <template v-slot="{ row }">
              <img v-if="row.staffPhoto" class="avatar" :src="row.staffPhoto" alt="">
              <image-holder v-else :scr="row.staffPhoto" class="avatar" />
            </template>
          </el-table-column>
          <el-table-column
            prop="workNumber"
            label="工号"
          />
          <el-table-column
            label="聘用方式"
          >
            <template v-slot="{row}">
              <!-- {{ row.formOfEmployment===1 ? '正式' : '非正式' }} -->
              {{ formOfEmployment(row.formOfEmployment) }}
              <!-- {{ historyMap[row.formOfEmployment] || "未知" }} -->
            </template>
          </el-table-column>
          <el-table-column
            prop="departmentName"
            label="部门"
          />
          <el-table-column
            prop="timeOfEntry"
            sortable
            label="入职时间"
          >
            <template v-slot="{row}">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="280px"
          >
            <template v-slot="{row}">

              <!-- 路径字符串拼接 -->
              <el-button type="text" size="small" @click="$router.push('employees/detail/' +row.id)">查看</el-button>

              <!-- query 传参 -->
              <!-- <el-button
                type="text"
                size="small"
                @click="$router.push({
                  path:'employees/detail',
                  query:{id:row.id}
                })"
              >查看</el-button> -->

              <!-- params 传参  路由需要设置 name -->
              <!-- <el-button
                type="text"
                size="small"
                @click="$router.push({
                  name:'detail',
                  params:{id:row.id}
                })"
              >查看</el-button> -->
              <el-button v-allow="'assign_roles'" type="text" size="small" @click="hAssign(row.id)">分配角色</el-button>
              <el-button v-allow="'delete_employees'" type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="box">
          <el-pagination
            :current-page="q.page"
            :page-sizes="[10, 15, 20, 30]"
            :page-size="q.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

      </el-card>
    </div>
    <el-dialog
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :visible.sync="showDialog"
      title="新增员工"
      width="40%"
      @closed="hClosed"
    >
      <empDialog ref="empDialog" @close="showDialog=false" @success="hSuccess" />
    </el-dialog>

    <el-dialog
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :visible.sync="showDialogRole"
      title="新增员工"
      width="40%"
      @closed="$refs.assignRole.resetIds()"
    >
      <assignRole :id="curId" ref="assignRole" @close="showDialogRole=false" />
    </el-dialog>
  </div>
</template>
<script>
import { getEmployees, delEmployee } from '@/api/employees'
import employeesConst from '@/constant/employees'
import empDialog from '@/views/employees/empDialog.vue'
import assignRole from '@/views/employees/assignRole.vue'
import dayjs from 'dayjs'
const historyMap = {}
employeesConst.hireType.forEach(item => {
  historyMap[item.id] = item.value
})
export default {
  components: {
    empDialog,
    assignRole
  },
  data() {
    return {
      showDialogRole: false,
      showDialog: false,
      employees: [],
      q: {
        page: 1,
        size: 10
      },
      total: 0,
      curId: ''
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    async  loadEmployees() {
      const res = await getEmployees(this.q)
      // console.log(res)
      this.employees = res.data.rows
      this.total = res.data.total
    },
    formOfEmployment(code) { // code=== 1  code=== 2
    // 去常量中找到对应的中文  并返回
      // const result = employeesConst.hireType.find(item => item.id === code)
      // // 提高代码的健壮性
      // if (result) {
      //   return result.value
      // } else {
      //   return '未知'
      // }
      return historyMap[code]
    },
    // 设置分页
    handleSizeChange(size) {
      this.q.size = size
      this.loadEmployees()
    },
    handleCurrentChange(page) {
      this.q.page = page
      this.loadEmployees()
    },
    // 删除功能
    async hDel(id) {
      try {
        // const result = await this.$confirm('真的要删除吗？', '提示', { type: 'warning' })
        //   .catch(e => e)
        // if (result !== 'confirm') return

        // 提醒用户
        await this.$confirm('真的要删除吗？', '提示', { type: 'warning' })
        // 发送请求
        const res = await delEmployee(id)
        // 根据结果提醒用户
        this.$message.success(res.message)
        // 处理分页
        if (this.employees.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        // 更新列表
        this.loadEmployees()
      } catch (e) {
        // console.log(e)
        if (e === 'cancel') return
        this.$message.error(e.message)
      }
    },
    hSuccess() {
      this.showDialog = false
      // 判断最后一页是否满了
      // this.q.page = 最后一页
      if (this.total % this.q.size === 0) {
        this.total++
      }
      this.q.page = Math.ceil(this.total / this.q.size)

      this.loadEmployees()
    },
    // 格式化时间
    formatDate(date) {
      // console.log(date)
      return dayjs(date).format('YYYY-DD-MM')
    },
    // 清空子组件的表单
    hClosed() {
      // 使用子组件上到方法
      this.$refs.empDialog.resetForm()
    },

    // 导出 Excel
    async hExport() {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1、发请求 获取所有数据

      const res = await getEmployees({ page: 1, size: this.total })
      console.log(res)
      const list = res.data.rows

      // 遍历 list 找到每一个元素，将其属性名转为中文
      // const zhList = list.map(enObj => {
      //   const zhObj = {}
      //   const enKeys = Object.keys(enObj)
      //   enKeys.forEach(enKey => {
      //     const zhKey = mapInfo[enKey]
      //     zhObj[zhKey] = enObj[enKey]
      //   })
      //   return zhObj
      // })

      // 取出第一个数据
      // const first = zhList[0]
      const first = list[0]
      if (!first) return
      // 取出 header
      // const header = Object.keys(first)
      const header = Object.keys(first).map(enKey => mapInfo[enKey])

      // const data = zhList.map(item => {
      //   const code = item['聘用形式']
      //   item['聘用形式'] = historyMap[code]
      //   return Object.values(item)
      // })
      const data = list.map(item => {
        const code = item['formOfEmployment']
        item['formOfEmployment'] = historyMap[code]
        return Object.values(item)
      })

      // 2、 导出 Excel（表头英文转中文）
      const excel = await import('@/vendor/Export2Excel')
      excel.export_json_to_excel({
        header: header, // 表头 ， 传入一个数组
        data: data, // 数据，传入一个二维数组
        filename: '在职员工列表', // 导出文件名
        autoWidth: true, // 宽度自适应
        bookType: 'xlsx' // 导出文件类型
      })

      //  import('@/vendor/Export2Excel').then(excel => {
      //   excel.export_json_to_excel({
      //     header: ['姓名', '职业'], // 表头 ， 传入一个数组
      //     data: [['黄陂威子', '推拿师'], ['刘谦', '魔术师'], ['黄鼠狼', 'Tony师傅']], // 数据，传入一个二维数组
      //     filename: '黄陂在逃人员', // 导出文件名
      //     autoWidth: true, // 宽度自适应
      //     bookType: 'xlsx' // 导出文件类型
      //   })
      // })
    },
    // 点击分配角色
    hAssign(id) {
      // console.log('这是要分配角色的ID:', id)
      this.showDialogRole = true
      this.curId = id
      // 给子组件设置 ref 就可以调用 子组件身上的方法
      this.$nextTick(() => {
        this.$refs.assignRole.loadRolesIds()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.box{
 text-align: center;
  margin-top: 10px;
}
</style>
